package com.voxel.sense.infomsg.module.task.send;

import android.app.Activity;
import android.content.Intent;
import android.os.Handler;
import android.text.TextUtils;
import android.util.Log;

import com.example.com.common.app.BasePresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.ListUtil;
import com.example.com.common.utils.NetworkUtils;
import com.example.com.common.utils.TaskUtils;
import com.example.com.common.utils.ToastUtil;
import com.voxel.sense.infomsg.R;
import com.voxel.sense.infomsg.data.bean.ConditionBean;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import cyy.example.com.facotry.Factory;
import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.constants.IntentConstants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.FirmNameByIdEntity;
import cyy.example.com.facotry.model.api.response.SearchMenuEntity;
import cyy.example.com.facotry.model.api.response.TaskDetailsInfoEntity;
import cyy.example.com.facotry.model.api.response.TaskUserGroupEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.NetHelper;
import cyy.example.com.facotry.net.helper.TaskNetHelper;

/**
 * @author ChenYiYao
 * @date 2018/5/14
 * des :  派发任务P层
 */
public class SendTaskPresenter extends BasePresenter<SendTaskActivity>
        implements SendTaskContract.Presenter, DataSource.Callback<BaseEntity> {

    private List<SearchMenuEntity.StaticSystemConstantDetailsBean> mTaskTypies;
    private List<SearchMenuEntity.StaticSystemConstantDetailsBean> mTaskLeviesDatas;

    //标记是否在加载公司列表
    private boolean mIsLoadFirmDatas = false;
    //标记是否第一次加载数据
    private boolean mFirstLoadFirmDatas = true;

    //标记是否在加载用户列表数据
    private boolean mIsLoadUserDatas = false;
    //标记是否在加第一次加载用户列表数据
    private boolean mFirstLoadUserDatas = true;

    //公司列表数据
    private List<FirmNameByIdEntity> mFirmDatas;
    //用户列表数据
    private List<ConditionBean> mUserDatas = new ArrayList();


    public SendTaskPresenter(SendTaskActivity view) {
        super(view);
    }


    @Override
    public void doLoadTaskDetailsInfo(String taskNumb) {
        String roleType = QueryConfigManager.getInstance().getTaskRoleOrganizationId();
        TaskNetHelper.getTaskDetailsInfo(taskNumb, roleType, this);
    }

    public  int taskType = 0;

    public  int getTaskType() {
        return taskType;
    }

    public  void setTaskType(int taskType) {
        this.taskType = taskType;
    }


    @Override
    public void doGetTaskType(int type) {
        //从配置管理器中获取数据
        if (mTaskTypies == null || mTaskTypies.size() < 1) {
            SearchMenuEntity taskType = QueryConfigManager.getInstance().getTaskType();
            if (taskType != null) {
                mTaskTypies = taskType.getStaticSystemConstantDetails();
            }
        }
        //可能获取到空的数据，所以需要判断
        if (mTaskTypies != null && mTaskTypies.size() > 0) {
            List<String> datas = new ArrayList<>();
            List<String> indexData = new ArrayList<>();
            Map<String, String> map = new HashMap<String, String>();
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : mTaskTypies) {
                Log.e("+++","任务"+bean.getConstantName()+"  /// "+bean.getConstantCode());
                datas.add(bean.getConstantName());
                indexData.add(bean.getConstantCode());
                map.put(bean.getConstantName(), bean.getConstantCode());
            }
            //任务
            taskType = type;
//            Collections.reverse(datas);
            mView.onShowTaskType(datas, indexData, map, type);
        } else {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败");
        }
    }

    private int levelType = 0;
    @Override
    public void doGetTaskLevel(int type) {
        //从管理器中获取数据
        if (mTaskLeviesDatas == null) {
            SearchMenuEntity taskLevel = QueryConfigManager.getInstance().getTaskLevel();
            if (taskLevel != null) {
                mTaskLeviesDatas = taskLevel.getStaticSystemConstantDetails();
            }
        }

        //组装数据
        if (mTaskLeviesDatas != null && mTaskLeviesDatas.size() > 0) {
            List<String> datas = new ArrayList<>();
            List<String> dataIndex = new ArrayList<>();
            Map<String, String> map = new HashMap<>();
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : mTaskLeviesDatas) {
                datas.add(bean.getConstantName());
                dataIndex.add(bean.getConstantCode());
                map.put(bean.getConstantName(), bean.getConstantCode());
            }
            levelType = type;
            mView.onShowTaskLevel(datas,dataIndex, map ,type);
        } else {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败");
        }
    }

    @Override
    public void doGetFirmList() {
        /**
         * 先判断是否在加载数据
         * 再则判断数据是否已存在
         */
        if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
        } else if (mIsLoadFirmDatas) {
            mView.showLoading("");
            mFirstLoadFirmDatas = false;
        } else if (mFirmDatas == null || mFirmDatas.size() < 1) {
            mIsLoadFirmDatas = true;
            NetHelper.getSearchFirmById("", this);
            mView.showLoading("");
        } else {
            mView.onShowFirmList(mFirmDatas);
        }
    }

    @Override
    public void doGetUserList() {
        if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
        } else if (mIsLoadUserDatas) {
            mView.showLoading("");
            mFirstLoadUserDatas = false;
        } else if (mUserDatas == null || mUserDatas.size() < 1) {
            TaskNetHelper.getTaskUserGroup(this);
            mIsLoadUserDatas = true;
            mView.showLoading("");
        } else {
            mView.onShowUserList(mUserDatas);
        }
    }

    @Override
    public void doSubmitTask(String name, long endTime, int taskTypePosition,
                             int lLevelPosition, String content, List<String> firms, List<String> user) {
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showToastLong(Factory.app(), "请填写任务名称");
        } else if (taskTypePosition == -1) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务类型");
        } else if (lLevelPosition == -1) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务级别");
        } else if (ListUtil.isEmpty(firms)) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务所属企业");
        } else if (ListUtil.isEmpty(user)) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务执行人");
        } else if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
        } else {
            mView.showLoading("");


            TaskNetHelper.SendTask(user, firms, endTime, name, String.valueOf(lLevelPosition),
              String.valueOf(taskTypePosition) , content, this);
        }
    }

    @Override
    public void doAlterTask(String taskNumb, String taskId, String name, long endTime, int taskTypePosition, int levelPosition, String content, List<String> user) {
        if (TextUtils.isEmpty(name)) {
            ToastUtil.showToastLong(Factory.app(), "请填写任务名称");
        } else if (taskTypePosition == -1) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务类型");
        } else if (levelPosition == -1) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务级别");
        } else if (ListUtil.isEmpty(user)) {
            ToastUtil.showToastLong(Factory.app(), "请选择任务执行人");
        } else if (!NetworkUtils.isConnected()) {
            ToastUtil.showToastLong(Factory.app(), Factory.app().getString(R.string.network_unavailable));
        } else {
            String userIdStr = "";
            for (String id : user) {
                userIdStr = TextUtils.isEmpty(userIdStr) ? id : userIdStr + "," + id;
            }
//            String levelCode = mTaskLeviesDatas.get(levelPosition).getConstantCode();
//            String typeCode = mTaskTypies.get(taskTypePosition).getConstantCode();
            TaskNetHelper.alterNoAcceptTask(userIdStr, endTime, name, String.valueOf(levelPosition), String.valueOf(taskTypePosition), content, taskNumb, taskId, this);
        }

    }


    @Override
    public void onDataLoaded(BaseEntity entity, int reqId) {
        if (mView == null) {
            return;
        }
        if (reqId == RequestIdFactory.SEARCH__FIRM_NAME_ID) {
            handleFirmDatas(entity);
        } else if (reqId == RequestIdFactory.GET_USER_TASK_GROUP) {
            handleUserGroupData(entity);
        } else if (reqId == RequestIdFactory.SEND_TASK) {
            if (entity.isSuccess()) {
                mView.onSubmitSuccess();
            } else {
                ToastUtil.showToastLong(Factory.app(), "派发失败，请重新再试");
            }
        } else if (reqId == RequestIdFactory.GET_TASK_DETAILS_INFO) {
            handleTaskInfo(entity);
        } else if (reqId == RequestIdFactory.ALTER_TASK_INFO) {
            if (entity.isSuccess()) {
                mView.onSubmitSuccess();
            } else {
                ToastUtil.showToastLong(Factory.app(), "修改失败，请重新再试");
            }
        }

        mView.dimissLoading();
    }

    private void handleTaskInfo(BaseEntity entity) {
        if (entity.isSuccess()) {
            TaskDetailsInfoEntity infoEntity = (TaskDetailsInfoEntity) entity.getData();
            TaskDetailsInfoEntity.TaskBaseInfoVoBean taskBaseInfoVo = infoEntity.getTaskBaseInfoVo();
            String taskObjects = taskBaseInfoVo.getTaskObjects();

            //获取任务所选公司的实体
            List<FirmNameByIdEntity> firmDatas = new ArrayList<>();
            getTaskFirmObject(taskObjects, firmDatas);

            //获取用户列表
            List<TaskDetailsInfoEntity.UserPacketBasicInfoVoBean> userList = infoEntity.getUserPacketBasicInfoVo();
            List<ConditionBean> taskUser = new ArrayList<>();
            if (!ListUtil.isEmpty(userList)) {
                taskUser = getTakeTaskUser(userList);
            }


            int levelPosition = getLevelPosition(taskBaseInfoVo.getTaskDegree());
            //获取任务等级的描述文字
            String LevelDesc = mTaskLeviesDatas.get(levelPosition).getConstantName();

            int typePosition = getTypePosition(taskBaseInfoVo.getTaskType());
            String typeDesc = mTaskTypies.get(typePosition).getConstantName();

            String type = taskBaseInfoVo.getTaskType();

            String taskContents = taskBaseInfoVo.getTaskContents();
            String taskName = taskBaseInfoVo.getTaskName();
            String endTime = taskBaseInfoVo.getEndTime();
            if (TextUtils.isEmpty(taskName) || TextUtils.isEmpty(endTime) || TextUtils.isEmpty(LevelDesc) || TextUtils.isEmpty(typeDesc) ||
                    ListUtil.isEmpty(firmDatas) || ListUtil.isEmpty(mUserDatas)) {
                mView.onGetTaskInfoFailure("数据出错，请重新再试");
            } else {
                mView.onRefreshView(taskName, endTime, Integer.parseInt(taskBaseInfoVo.getTaskDegree()), LevelDesc, TaskUtils.changeTaskString(taskBaseInfoVo.getTaskType()), typeDesc, firmDatas, taskUser, taskContents);
            }
        } else {
            mView.onGetTaskInfoFailure("数据出错，请重新再试");
        }
    }

    /**
     * 分割字符，获取公司实体
     *
     * @param taskObjects
     * @param datas
     */
    private void getTaskFirmObject(String taskObjects, List<FirmNameByIdEntity> datas) {
        String[] split = taskObjects.split(":");
        String firmId = "";
        String firmName = "";
        if (split != null && split.length >= 2) {
            firmId = split[0];
            firmName = split[1];
            FirmNameByIdEntity firmEntity = new FirmNameByIdEntity();
            firmEntity.setCompanyId(firmId);
            firmEntity.setCompanyName(firmName);
            datas.add(firmEntity);
        } else {
            mView.onGetTaskInfoFailure("获取数据失败");
        }
    }

    /**
     * 获取指定的任务类型所在集合中的index
     *
     * @param type 指定的类型id
     */
    private int getTypePosition(String type) {
        int position = -1;
        //从配置管理器中获取数据
        if (mTaskTypies == null || mTaskTypies.size() < 1) {
            SearchMenuEntity taskType = QueryConfigManager.getInstance().getTaskType();
            if (taskType != null) {
                mTaskTypies = taskType.getStaticSystemConstantDetails();
            }
        }
        //可能获取到空的数据，所以需要判断
        if (mTaskTypies != null && mTaskTypies.size() > 0) {
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : mTaskTypies) {
                position++;
                if (bean.getConstantCode().equals(type)) {
                    return position;
                }
            }
        }
        return position;
    }

    /**
     * 获取指定的任务等级所在集合在的index
     *
     * @param LevelId 指定的等级id
     * @return
     */
    private int getLevelPosition(String LevelId) {
        int position = -1;
        //从管理器中获取数据
        if (mTaskLeviesDatas == null) {
            SearchMenuEntity taskLevel = QueryConfigManager.getInstance().getTaskLevel();
            if (taskLevel != null) {
                mTaskLeviesDatas = taskLevel.getStaticSystemConstantDetails();
            }
        }
        //组装数据
        if (mTaskLeviesDatas != null && mTaskLeviesDatas.size() > 0) {
            List<String> datas = new ArrayList<>();
            for (SearchMenuEntity.StaticSystemConstantDetailsBean bean : mTaskLeviesDatas) {
                position++;
                if (bean.getConstantCode().equals(LevelId)) {
                    break;
                }
                datas.add(bean.getConstantName());
            }

        }
        return position;
    }

    /**
     * 从用户列表中获取已选中的用户
     *
     * @param userList
     * @return
     */
    private List<ConditionBean> getTakeTaskUser(List<TaskDetailsInfoEntity.UserPacketBasicInfoVoBean> userList) {
        List<ConditionBean> beans = new ArrayList<>();
        for (TaskDetailsInfoEntity.UserPacketBasicInfoVoBean infoBean : userList) {
            List<TaskDetailsInfoEntity.UserPacketBasicInfoVoBean.UserBasicInfoBean> userBasicInfo = infoBean.getUserBasicInfo();
            if (!ListUtil.isEmpty(userBasicInfo)) {
                //缓存用户列表
                mUserDatas.add(new ConditionBean(Constants.HEAD_ITEM, "", infoBean.getPacketName(), false));
                for (TaskDetailsInfoEntity.UserPacketBasicInfoVoBean.UserBasicInfoBean user : userBasicInfo) {
                    //遍历每个用户，进行重新组装数据
                    String desc = TextUtils.isEmpty(user.getRealname()) ? user.getUsername() : user.getUsername() + "(" + user.getRealname() + ")";
                    ConditionBean conditionBean = new ConditionBean(Constants.NORMAL_ITEM, user.getUserId(), desc, false);
                    mUserDatas.add(new ConditionBean(Constants.NORMAL_ITEM, user.getUserId(), desc, user.isIdentificationCode()));
                    if (user.isIdentificationCode()) {
                        beans.add(conditionBean);
                    }
                }
            }
        }

        return beans;
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null) {
            return;
        }
        mView.dimissLoading();
        if (reqId == RequestIdFactory.SEARCH__FIRM_NAME_ID) {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败");
            changeFirmLIstLoadFlag();
        } else if (reqId == RequestIdFactory.GET_USER_TASK_GROUP) {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败");
            changeUserGroupLoadFlag();
        } else if (reqId == RequestIdFactory.SEND_TASK) {
            ToastUtil.showToastLong(Factory.app(), "派发失败，请重新再试");
        }else if (reqId == RequestIdFactory.GET_TASK_DETAILS_INFO) {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败，请重新加载");
            mView.onGetTaskInfoFailure("请重新加载");
        } else if (reqId == RequestIdFactory.ALTER_TASK_INFO) {
            mView.onGetTaskInfoFailure("修改失败");
        }
    }

    private void handleUserGroupData(BaseEntity entity) {
        if (entity.isSuccess()) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    //在子线程中处理数据
                    List<TaskUserGroupEntity> userList = (List<TaskUserGroupEntity>) entity.getData();
                    if (userList != null && userList.size() > 0) {
                        mUserDatas.clear();
                        for (TaskUserGroupEntity bean : userList) {
                            String packetName = bean.getPacketName();
                            //判断每个分组是否有用户，再进行添加
                            List<TaskUserGroupEntity.UserBasicInfoBean> infos = bean.getUserBasicInfo();
                            if (infos != null && infos.size() > 0) {
                                mUserDatas.add(new ConditionBean(Constants.HEAD_ITEM, "", packetName, false));
                                for (TaskUserGroupEntity.UserBasicInfoBean user : infos) {
                                    //遍历每个用户，进行重新组装数据
                                    String desc = TextUtils.isEmpty(user.getRealname()) ? user.getUsername() : user.getUsername() + "(" + user.getRealname() + ")";
                                    mUserDatas.add(new ConditionBean(Constants.NORMAL_ITEM, user.getUserId(), desc, false));
                                }
                            }
                        }
                    }
                    //切回主线程
                    new Handler(Factory.app().getMainLooper()).post(new Runnable() {
                        @Override
                        public void run() {
                            if (mUserDatas.size() > 0) {
                                handlederUserListFinish(mUserDatas);
                            } else {
                                mView.showSnackBarWarning("暂无可执行任务人员");
                                changeUserGroupLoadFlag();
                            }
                        }
                    });
                }
            }).run();

        } else {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败");
            changeUserGroupLoadFlag();
        }
    }

    //改变用户列表加载标记
    private void changeUserGroupLoadFlag() {
        mIsLoadUserDatas = false;
        mFirstLoadUserDatas = false;

    }

    private void handleFirmDatas(BaseEntity entity) {
        if (entity.isSuccess()) {
            mFirmDatas = (List<FirmNameByIdEntity>) entity.getData();
            handleFirmListFinish(mFirmDatas);
        } else {
            ToastUtil.showToastLong(Factory.app(), "获取数据失败");
            changeFirmLIstLoadFlag();
        }
    }

    private void handleFirmListFinish(List datas) {
        if (!mFirstLoadFirmDatas) {
            mView.onShowFirmList(datas);
        }
        changeFirmLIstLoadFlag();
    }

    private void handlederUserListFinish(List datas) {
        if (!mFirstLoadUserDatas) {
            mView.onShowUserList(datas);
        }
        changeUserGroupLoadFlag();
    }


    private void changeFirmLIstLoadFlag() {
        mIsLoadFirmDatas = false;
        mFirstLoadFirmDatas = false;
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IntentConstants.FIRM_SELECT_LIST && resultCode == Activity.RESULT_OK) {
            //处理从公司选择界面返回的数据
            mFirmDatas = data.getParcelableArrayListExtra(IntentConstants.LIST_TYPE);
            //已选中的数据
            List<FirmNameByIdEntity> datas = data.getParcelableArrayListExtra(IntentConstants.EXTRAX_DATA);
            mView.onRefreshSelectionFirms(datas);

        } else if (requestCode == IntentConstants.USER_SELECT_LIST && resultCode == Activity.RESULT_OK) {
            //处理从用户界面返回的数据
            mUserDatas = data.getParcelableArrayListExtra(IntentConstants.LIST_TYPE);
            //已选中的数据
            List<ConditionBean> datas = data.getParcelableArrayListExtra(IntentConstants.EXTRAX_DATA);
            mView.onRefreshSelectionUsers(datas);

        }
    }


}
